package com.dlm.controller;

import com.dlm.service.IUserCouponService;
import com.dlm.service.impl.UserCouponServiceImpl;
import com.dlm.util.RegCodeUtil;
import com.dlm.util.SMSUtil;
import com.google.common.base.Preconditions;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

/**
 * Created by chongsong on 15/2/1.
 * <mailto>chong.song@autonavi.com</mailto>
 */
public class SMSController extends BaseController {
    private Logger logger = Logger.getLogger(SMSController.class);

    private IUserCouponService userCouponService = new UserCouponServiceImpl();

    public void sendRegSMS(){
        long phone = getParaToLong("phone");
        try{
            //间隔低于60S,不允许发送.
            Object preTime = getSession().getAttribute("regCodePreTime");
            if(preTime != null  && (Long)preTime + 60000 > System.currentTimeMillis()){
                renderJson(makeDto(1, "发送间隔为60秒!", null));
                return;
            }
            // 测试用设置openid为1
//            getSession().setAttribute("openid","1");
            Preconditions.checkArgument(phone != 0,"手机号必须输入!");
            String code = RegCodeUtil.makeRegCode();
            System.out.println("******" + code);
            SMSUtil.sendSMS(phone,SMSUtil.makeRegCodeString(code));
            getSession().setAttribute("regCode", code);
            getSession().setAttribute("phone",phone);
            getSession().setAttribute("regCodePreTime",System.currentTimeMillis());
            renderJson(makeDto(0, "ok", null));
        }catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    public void checkCode(){
        String code = getPara("code");
        try{
            Preconditions.checkArgument(StringUtils.isNotBlank(code),"code必须输入!");
            Object regCode = getSession().getAttribute("regCode");
            if(regCode != null && code.equals(regCode)) {
                long phone = (Long)getSession().getAttribute("phone");
                String openid = (String)getSession().getAttribute("openid");
                System.out.println(phone + "  " + openid);
                if(StringUtils.isNotBlank(openid)){
                    usersService.updateTel(phone,openid);
                    userCouponService.addNewUserCoupon(phone);
                    renderJson(makeDto(0, "ok", null));
                    return;
                }
            }
        }catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        renderJson(makeDto(1, "验证失败!", null));
    }

    public void reg(){
        findUser();
        redirect("/#/reg");
    }

}
